import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zhuanzu/utils/logger.dart';

import '../provider/UnauthorizedException.dart';

class Api {

   static const String wsBaseUrl = 'ws://114.215.188.208:9088/ws'; // 👈 专为 WebSocket 准备

  static const String baseUrl = 'http://114.215.188.208:8080/api';

  /// 动态获取请求头（包含 token）
  static Future<Map<String, String>> _getHeaders() async {
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString('token');

    Map<String, String> headers = {'Content-Type': 'application/json'};
    if (token != null) {
      headers['satoken'] = token;
    }

    return headers;
  }

  static Future<Map<String, dynamic>> get(
    String path, {
    Map<String, Object>? params,
  }) async {
    final fixedParams = params?.map((key, value) {
      return MapEntry(key, value.toString() ?? '');
    });
    final uri = Uri.parse(
      '$baseUrl$path',
    ).replace(queryParameters: fixedParams);
    final headers = await _getHeaders();

    final response = await http.get(uri, headers: headers);
    return _handleResponse(response);
  }

  static Future<Map<String, dynamic>> post(
    String path, {
    Map<String, dynamic>? body,
  }) async {
    final uri = Uri.parse('$baseUrl$path');
    final headers = await _getHeaders();

    final response = await http.post(
      uri,
      headers: headers,
      body: jsonEncode(body ?? {}),
    );
    return _handleResponse(response);
  }

  static Future<Map<String, dynamic>> postForm(
    String path, {
    Map<String, Object>? params,
  }) async {
    final uri = Uri.parse('$baseUrl$path');
    final headers = await _getHeaders();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';

    final bodyString = params != null
        ? Uri(
            queryParameters: params.map((k, v) => MapEntry(k, v.toString())),
          ).query
        : '';

    final response = await http.post(uri, headers: headers, body: bodyString);
    return _handleResponse(response);
  }

  static Future<String?> uploadImage(File file) async {
    final uri = Uri.parse('$baseUrl/upload');
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString('token');

    final request = http.MultipartRequest('POST', uri);
    if (token != null) {
      request.headers['satoken'] = token;
    }

    Log.d('上传图片 请求 URL: $uri');
    Log.d('上传图片 请求头: ${request.headers}');

    request.files.add(await http.MultipartFile.fromPath('file', file.path));

    try {
      final streamedResponse = await request.send();
      final responseBody = await streamedResponse.stream.bytesToString();

      if (streamedResponse.statusCode == 200) {
        final json = jsonDecode(responseBody);
        Log.d('上传图片 请求 结果: $json');
        return json['data'];
      } else {
        throw Exception('上传失败 [${streamedResponse.statusCode}]: $responseBody');
      }
    } catch (e) {
      Log.d(e);
      return null;
    }
  }

  static Future<Map<String, dynamic>> delete(
    String path, {
    Map<String, dynamic>? body,
  }) async {
    final uri = Uri.parse('$baseUrl$path');
    final headers = await _getHeaders();

    final response = await http.delete(
      uri,
      headers: headers,
      body: jsonEncode(body ?? {}),
    );
    return _handleResponse(response);
  }

  static Future<Map<String, dynamic>> put(
    String path, {
    Map<String, dynamic>? body,
  }) async {
    final uri = Uri.parse('$baseUrl$path');
    final headers = await _getHeaders();

    final response = await http.put(
      uri,
      headers: headers,
      body: jsonEncode(body ?? {}),
    );
    return _handleResponse(response);
  }

  static Map<String, dynamic> _handleResponse(http.Response response) {
    final body = jsonDecode(response.body);
    final statusCode = body["code"];

    if (statusCode == 401 || statusCode == 403) {
      throw UnauthorizedException();
    }
    return body;
  }
}
